package com.jltx.xq.relaxnewspro.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.jltx.xq.relaxnewspro.R;
import com.jltx.xq.relaxnewspro.utils.HttpUtil;
import com.jltx.xq.relaxnewspro.utils.Settings;

/**
 * Created by bo on 2017/5/14.
 */

public abstract class BaseWebViewActivity extends AppCompatActivity {
    protected WebView webView;
    protected ProgressBar progressBar;
    protected boolean isLoading = true;
    protected String data;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        initData();
    }
    protected abstract String getData();
    protected abstract void loadData();
    private void initData(){
        data = getData();
        webView = (WebView) findViewById(R.id.webview_act_webview);
        progressBar = (ProgressBar) findViewById(R.id.probar_act_webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportMultipleWindows(false);
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);

        if(HttpUtil.isWIFI == false){
            webView.getSettings().setBlockNetworkImage(Settings.getsInstance().getBoolean(Settings.NO_PIC_MODE, false));
        }else {
            webView.getSettings().setBlockNetworkImage(false);
        }

        loadData();
        setProgressBarIndeterminateVisibility(true);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.GONE);
            }
        });
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if(isLoading){
                    progressBar.incrementProgressBy(newProgress - progressBar.getProgress());
                    if (newProgress > 25){
                        isLoading = false;
                        progressBar.setVisibility(View.GONE);
                    }
                }
            }
        });
    }
}
